package com.kylin.module.admin.business;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.kylin.common.dict.orm.CatDict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.util.MemObjFactory;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.module.admin.form.CatDictForm;

public class ManageCatDictBlogic {
	private int psgeSize = 15;
	protected static Logger log = Logger.getLogger(ManageCatDictBlogic.class);

	public DisplayPage getCatDictList(int pageNum, CriteriaInfo cinfo) throws BusinessException {
		log.info("search cat page " + pageNum);
		DisplayPage page = PageManager.getDisplayPage(psgeSize, pageNum, cinfo);
		return page;
	}

	public void addCatDict(CatDictForm form)throws BusinessException{
		CatDict cat = new CatDict();
		List same = BaseHibernateDAO.findByProperty(CatDict.class, "name",form.getName());
		if(same != null && same.size() > 0)
			throw new BusinessException("msg.manage.saveCatDict.existsame");
		try{
			cat.setCreatedon(new Date());
			if(form.getHasSub() != null && form.getHasSub().equals("on"))
				cat.setHassub(new Integer(1));
			else
				cat.setHassub(new Integer(0));
			cat.setLanguage(form.getLanguage());
			cat.setName(form.getName());
			cat.setOrdering(form.getOrdering());
			BaseHibernateDAO.save(cat);
			MemObjFactory.reloadDict(cat);
		}catch(BusinessException e){
			throw new BusinessException("msg.manage.saveCatDict.fail",e);
		}
	}

	public void updateCatDict(CatDictForm form)throws BusinessException{
		log.info("更新 catdict updateCatDict()");
		try{
			CatDict cat = (CatDict) BaseHibernateDAO.findById(CatDict.class, form.getId());
			cat.setCreatedon(new Date());
			if(form.getHasSub() != null && form.getHasSub().equals("on"))
				cat.setHassub(new Integer(1));
			else
				cat.setHassub(new Integer(0));
			cat.setLanguage(form.getLanguage());
			cat.setName(form.getName());
			cat.setOrdering(form.getOrdering());
			BaseHibernateDAO.update(cat);
			MemObjFactory.reloadDict(cat);
		}catch(BusinessException e){
			throw new BusinessException("msg.manage.updateCatDict.fail",e);
		}
	}

	public CatDict getCatDictById(Long id) throws BusinessException {
		return (CatDict) BaseHibernateDAO.findById(CatDict.class, id);
	}
	
	public void deleteCatDictById(Long id) throws BusinessException {
		CatDict cat = (CatDict)BaseHibernateDAO.findById(CatDict.class, id);
		BaseHibernateDAO.delete(cat);
		MemObjFactory.reloadDict(cat);
	}
}
